package com.sram.controller.user;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.sram.controller.common.util.WordGenerator;
import com.sram.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sram.entity.User;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import sun.misc.BASE64Encoder;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.List;
import java.util.concurrent.*;

@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	private UserService userService;


	@RequestMapping(value="/login")
	public  @ResponseBody String regist( HttpServletRequest request,Model model, HttpServletResponse response,HttpSession session, User user) throws Exception {
		System.out.println(user);
		String mes =null;
		long a=System.currentTimeMillis();
//		测试多线程
//		getLogin();
//		测试开启事物的时间
		//testTrans(user);
//		userService.inserttest();
		List<User> dd =userService.getUserByName(user.getUserName(),user.getPassword());

		System.out.println("\r<br>执行耗时 : "+(System.currentTimeMillis()-a)/1000f+" 秒 ");


		if(dd.size() == 0){
			mes = "密码错误";
		}else{
			session.setAttribute("userId",dd.get(0).getId());
			session.setAttribute("userName",dd.get(0).getUserName());
			mes = "ok";
		}
		return mes;
	}

	private void testTrans(User user) {
//		for (int i = 0; i < 10000; i++) {
			List<User> dd =userService.getUserByName(user.getUserName(),user.getPassword());
//		}
	}

	public  void getLogin() {
		ExecutorService executor = Executors.newFixedThreadPool(3);
		List<Future<Long>> list = new ArrayList<Future<Long>>();
		for(long i=0; i < 2; i++){
			Callable<Long> worker = new testCallable(userService);
			// 提交并执行任务，任务启动时返回了一个Future对象，
			Future<Long> submit = executor.submit(worker);
			list.add(submit);
		}
		long sum = 0;
		for(Future<Long> future : list){
			try{
				// 获得第任务的结果，如果调用get方法，当前线程会等待任务执行完毕后才往下执行
				sum += future.get();
			}catch (InterruptedException e1){
				e1.printStackTrace();
			}catch(ExecutionException e2){
				e2.printStackTrace();
			}
		}
		executor.shutdown();
	}
	@RequestMapping(value="/out")
	public String out(HttpServletRequest request,HttpSession session){
		session.invalidate();
		return "redirect:/index.jsp";
	}
	@RequestMapping(value="/authCode")
	public void getAuthCode(HttpServletRequest request, HttpServletResponse response,HttpSession session)
			throws IOException {
		int width = 63;
		int height = 37;
		Random random = new Random();
		//设置response头信息
		//禁止缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		//生成缓冲区image类
		BufferedImage image = new BufferedImage(width, height, 1);
		//产生image类的Graphics用于绘制操作
		Graphics g = image.getGraphics();
		//Graphics类的样式
		g.setColor(this.getRandColor(200, 250));
		g.setFont(new Font("Times New Roman",0,28));
		g.fillRect(0, 0, width, height);
		//绘制干扰线
		for(int i=0;i<40;i++){
			g.setColor(this.getRandColor(130, 200));
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int x1 = random.nextInt(12);
			int y1 = random.nextInt(12);
			g.drawLine(x, y, x + x1, y + y1);
		}

		//绘制字符
		String strCode = "";
		for(int i=0;i<4;i++){
			String rand = String.valueOf(random.nextInt(10));
			strCode = strCode + rand;
			g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
			g.drawString(rand, 13*i+6, 28);
		}
		//将字符保存到session中用于前端的验证
		session.setAttribute("strCode", strCode);
		g.dispose();

		ImageIO.write(image, "JPEG", response.getOutputStream());
		response.getOutputStream().flush();

	}
	//创建颜色
	Color getRandColor(int fc,int bc){
		Random random = new Random();
		if(fc>255)
			fc = 255;
		if(bc>255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r,g,b);
	}
	/*----------------------------------------------------------*/
	@RequestMapping(value="/getAllUser")

	public String getAllUser(HttpServletRequest request,Model model) throws Exception {
		List<User> ss = userService.getAll();
		model.addAttribute("users",ss);
		return "allUser";
	}
	@RequestMapping(value="/toAddAndUpUser")
	public String toAddAndUpUser(HttpServletRequest request,Model model) throws Exception {
		String id = request.getParameter("id");
		if( id != null){
			User  user = (User) userService.selectByPrimaryKey(Integer.valueOf(id));
			model.addAttribute("user",user);
		}
		return "user/addAndUpUser";
	}
	@RequestMapping(value="/addAndUpUser")
	public String addAndUpUser(HttpServletRequest request,Model model,User user) throws Exception {
		if(user.getId() == null){
			userService.insert(user);
		}else{
			userService.updateByPrimaryKey(user);
		}

//		return "redirect:getAllUser.do";
		return null;
	}

	@RequestMapping(value="/delUser")
	public @ResponseBody String delUser(HttpServletRequest request,Model model) throws Exception {
		String id = request.getParameter("id");
		userService.deleteByPrimaryKey(Integer.valueOf(id));
		return "success";
	}
	@RequestMapping(value="/exportWord")
	public void exportWord(HttpServletRequest request, Model model, HttpServletResponse resp) throws Exception {
		request.setCharacterEncoding("utf-8");
		List<User> ss = userService.getAll();
		Map<String, Object> map = new HashMap<String, Object>();
		Enumeration<String> paramNames = request.getParameterNames();
		// 通过循环将表单参数放入键值对映射中
//		while(paramNames.hasMoreElements()) {
//			String key = paramNames.nextElement();
//			String value = request.getParameter(key);
//			map.put(key, value);
//		}
		map.put("id",String.valueOf(ss.get(0).getId()));
		map.put("userName",ss.get(0).getUserName());
		map.put("password",ss.get(0).getPassword() ==null ? "":ss.get(0).getPassword());
		map.put("age",ss.get(0).getAge() == null ? "":ss.get(0).getPassword());
		map.put("gender",ss.get(0).getGender() ==null ? "":ss.get(0).getPassword());

		// 提示：在调用工具类生成Word文档之前应当检查所有字段是否完整
		// 否则Freemarker的模板殷勤在处理时可能会因为找不到值而报错 这里暂时忽略这个步骤了
		File file = null;
		InputStream fin = null;
		ServletOutputStream out = null;
		try {
			// 调用工具类WordGenerator的createDoc方法生成Word文档
			file = WordGenerator.createDoc(map, "oneUser");
			fin = new FileInputStream(file);

			resp.setCharacterEncoding("utf-8");
			resp.setContentType("application/msword");
			// 设置浏览器以下载的方式处理该文件默认名为resume.doc
			resp.addHeader("Content-Disposition", "attachment;filename=oneUser.doc");

			out = resp.getOutputStream();
			byte[] buffer = new byte[512];  // 缓冲区
			int bytesToRead = -1;
			// 通过循环将读入的Word文件的内容输出到浏览器中
			while((bytesToRead = fin.read(buffer)) != -1) {
				out.write(buffer, 0, bytesToRead);
			}
		} finally {
			if(fin != null) fin.close();
			if(out != null) out.close();
			if(file != null) file.delete(); // 删除临时文件
		}
	}
	@RequestMapping(value="/exportAllWord")
	public void exportAllWord(HttpServletRequest request, Model model, HttpServletResponse resp) throws Exception {
		request.setCharacterEncoding("utf-8");
		List<User> ss = userService.getAll();
		//  用于组装word页面需要的数据
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("id",String.valueOf(ss.get(0).getId()));
		map.put("userName",ss.get(0).getUserName());
		map.put("password",ss.get(0).getPassword() ==null ? "":ss.get(0).getPassword());
		map.put("age",ss.get(0).getAge() == null ? "":ss.get(0).getPassword());
		map.put("gender",ss.get(0).getGender() ==null ? "":ss.get(0).getPassword());
		//word页面需要循环输出的东西
		List<Map<String, Object>> newsList=new ArrayList<Map<String,Object>>();
		for(int i=0;i<=ss.size()-1;i++){
			Map<String, Object> map1=new HashMap<String, Object>();
			map1.put("id",String.valueOf(ss.get(i).getId()));
			map1.put("userName",ss.get(i).getUserName());
			map1.put("password",ss.get(i).getPassword() ==null ? "":ss.get(0).getPassword());
			map1.put("age",ss.get(i).getAge() == null ? "":ss.get(0).getPassword());
			map1.put("gender",ss.get(i).getGender() ==null ? "":ss.get(0).getPassword());
			newsList.add(map1);
		}

		map.put("newsList",newsList);
		// 提示：在调用工具类生成Word文档之前应当检查所有字段是否完整
		// 否则Freemarker的模板殷勤在处理时可能会因为找不到值而报错 这里暂时忽略这个步骤了
		File file = null;
		InputStream fin = null;
		ServletOutputStream out = null;
		try {
			// 调用工具类WordGenerator的createDoc方法生成Word文档
			file = WordGenerator.createDoc(map, "userAll");
			fin = new FileInputStream(file);

			resp.setCharacterEncoding("utf-8");
			resp.setContentType("application/msword");
			// 设置浏览器以下载的方式处理该文件默认名为resume.doc
			resp.addHeader("Content-Disposition", "attachment;filename=oneUser.doc");

			out = resp.getOutputStream();
			byte[] buffer = new byte[512];  // 缓冲区
			int bytesToRead = -1;
			// 通过循环将读入的Word文件的内容输出到浏览器中
			while((bytesToRead = fin.read(buffer)) != -1) {
				out.write(buffer, 0, bytesToRead);
			}
		} finally {
			if(fin != null) fin.close();
			if(out != null) out.close();
			if(file != null) file.delete(); // 删除临时文件
		}
	}

    @RequestMapping(value="/exportWithPhoto")
    public void exportWithPhoto(HttpServletRequest request, Model model, HttpServletResponse resp) throws Exception {
        request.setCharacterEncoding("utf-8");
        List<User> ss = userService.getAll();
        Map<String, Object> map = new HashMap<String, Object>();
        Enumeration<String> paramNames = request.getParameterNames();

        map.put("id",String.valueOf(ss.get(0).getId()));
        map.put("userName",ss.get(0).getUserName());
        map.put("password",ss.get(0).getPassword() ==null ? "":ss.get(0).getPassword());
        map.put("age",ss.get(0).getAge() == null ? "":ss.get(0).getPassword());
        map.put("gender",ss.get(0).getGender() ==null ? "":ss.get(0).getPassword());
        map.put("image", getImageStr(request));
        // 提示：在调用工具类生成Word文档之前应当检查所有字段是否完整
        // 否则Freemarker的模板殷勤在处理时可能会因为找不到值而报错 这里暂时忽略这个步骤了
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            // 调用工具类WordGenerator的createDoc方法生成Word文档
            file = WordGenerator.createDoc(map, "exportWithPhoto");
            fin = new FileInputStream(file);

            resp.setCharacterEncoding("utf-8");
            resp.setContentType("application/msword");
            // 设置浏览器以下载的方式处理该文件默认名为resume.doc
            resp.addHeader("Content-Disposition", "attachment;filename=oneUser.doc");

            out = resp.getOutputStream();
            byte[] buffer = new byte[512];  // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } finally {
            if(fin != null) fin.close();
            if(out != null) out.close();
            if(file != null) file.delete(); // 删除临时文件
        }
    }
    private String getImageStr(HttpServletRequest request) {
        String imgFile = request.getSession().getServletContext().getRealPath("/")+"image/1.png";

//        String imgFile = "d:/1.png";

        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    /*----------------------------------------------------------*/
	@RequestMapping(value="/main")
	public String main(){
		return "main";
	}
	@RequestMapping(value="/chuanzhi")
	public String chuanzhi(){
		return "chuanzhi";
	}
	@RequestMapping(value="/getUser1")
	public String getUser1( Model model,User user){
		model.addAttribute("name",user.getUserName());
		model.addAttribute("pwd","dddddddddddd");
		return "chuanzhi";
	}
	@RequestMapping(value="/getUser2")
	public String getUser2(HttpServletRequest request, Model model,User user){
		String username = request.getParameter("userName");
		String password = request.getParameter("password");
		model.addAttribute("name",username);
		model.addAttribute("pwd",password);
		return "chuanzhi";
	}
	@RequestMapping(value="/getUser3")
	public void getUser3(HttpServletRequest request, Model model,HttpServletResponse response,User user) throws IOException {
		String username = request.getParameter("userName");
		System.out.printf("getUser3-----------"+username);
		model.addAttribute("name",username);
		response.getWriter().write("阿斯蒂芬");
		response.getWriter().flush();
	}
	@RequestMapping(value="/getUser4")
	public void getUser4(HttpServletRequest request, Model model,HttpServletResponse response,User user) throws IOException {
		String username = request.getParameter("userName");
		model.addAttribute("name",username);
		List ss = new ArrayList();
		ss.add(new User("ss","dd"));
		ss.add(new User("ss2","dd2"));
		System.out.printf("getUser4-----------"+ss.toString());
		response.getWriter().write(JSON.toJSONString(ss));
		response.getWriter().flush();
	}
	@RequestMapping(value="/getUser5")
	public  @ResponseBody String  getUser5(HttpServletRequest request, Model model,HttpServletResponse response,User user) throws IOException {
		String username = request.getParameter("userName");
//		return "ss";//中文乱码  ,produces = "application/json; charset=utf-8"  加上请求会反应慢
		return "杜浩";
	}
	@RequestMapping(value="/getUser6")
	public  @ResponseBody List<User> getUser6(HttpServletRequest request, Model model,HttpServletResponse response,User user) throws IOException {
		String username = request.getParameter("userName");
		model.addAttribute("name",username);
		List ss = new ArrayList();
		ss.add(new User("胜多负少","dd"));
		ss.add(new User("水电费","dd2"));
		return ss;
	}
	@RequestMapping(value="/redirect")
	public  String redirect(RedirectAttributes attr) throws IOException {
		// 重定向中文乱码问题server.xml 设置URIEncoding="UTF-8"
		attr.addAttribute("ss","杜浩");
		return "redirect:redirect2.do";
	}
	@RequestMapping(value="/redirect2")
	public  String userList2(HttpServletRequest request, Model model,HttpServletResponse response,User user) throws IOException {
		System.out.println("redirect2................"+ request.getParameter("ss"));
		return "redirect";
	}
}
class testCallable implements Callable {
	private UserService userService;
	public testCallable(UserService userService){
		this.userService = userService;
	}
	public Long call()throws Exception{
		userService.inserttest();
		return Long.valueOf(1);
	}
}